﻿
using NicoView.Model.Share.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace NicoView.Model.Share.Speech.Learn
{
    public sealed class RegexLearnDictionary:LearnDictionary
    {
        public RegexLearnDictionary()
        {
            LearnRegex = null;
        }

        public void Add(string key, string val)
        {
            this.Add(key, new Learnword(key, val));
        }

        public new void Add(string key,Learnword word)
        {
            base.Add(key, word);
            _learnRegexReset();

        }

        public new void Set(ICollection<Learnword> words)
        {
            base.Set(words);
            _learnRegexReset();
        }

        public new void Remove(string key)
        {
            base.Remove(key);
            _learnRegexReset();
        }

        private void _learnRegexReset()
        {
            StringBuilder builder = new StringBuilder();

            for (int index = 0; index < this.Count(); index++)
            {
                builder.Append('(');
                builder.Append(this.Values.ElementAt(index).Key);
                builder.Append(')');
                if(index<this.Count()-1) builder.Append('|');
            }

            LearnRegex = new Regex(builder.ToString());
            
        }

        public override string Replace(string text)
        {
            foreach (var key in this.Keys)
            {
                var regex = new Regex(key);

                text = regex.Replace(text, this[key].Text);

            }

            return text;
        }

        public Regex LearnRegex { get; private set; }


        public static readonly RegexLearnDictionary SystemRegexLearnDictionary = _initalizeSystemRegexLearnDictionary();

        private static RegexLearnDictionary _initalizeSystemRegexLearnDictionary()
        {
            var dic = new RegexLearnDictionary();
            dic.Add(NicoFormat.URL_FORMAT, "URL省略");
            dic.Add(NicoFormat.HTML_TAG, "");
            dic.Add(NicoFormat.COMMENT_COMMAND_FORMAT, "");
            return dic;
        }

        public void Initalize()
        {
            this.Add("[wｗ](([wｗ])|($))", "わら");
        }

    }
}
